package com.share.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class LoginFilter
 */
@WebFilter("/jsp/login/login.jsp")
public class AutoLoginFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public AutoLoginFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("进入AutoLoginFilter");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		Cookie[] cookies = req.getCookies();
		String sLoginName = null;
		String sPassword = null;
		System.out.println("AutoLoginFilter.cookies!=null--" + (cookies != null));
		if (cookies != null) {
			System.out.println("AutoLoginFilter.cookies.length--" + cookies.length);
			for (Cookie cookie : cookies) {
				System.out.println("AutoLoginFilter.cookie.equals(loginUser)--" + cookie.getName().equals("loginUser"));
				System.out.println("AutoLoginFilter.cookie.name--" + cookie.getName());
				if (cookie.getName().equals("loginUser")) {
					String[] info = cookie.getValue().split("==");
					sLoginName = info[0];
					sPassword = info[1];
					System.out.println("AutoLoginFilter.cookie.value.sLoginName--" + sLoginName);
					System.out.println("AutoLoginFilter.cookie.value.sPassword--" + sPassword);
				}
			}
			req.setAttribute("sLoginName", sLoginName);
			req.setAttribute("sPassword", sPassword);
			req.getRequestDispatcher("../../login/login.action").forward(req, res);
		} else {
			chain.doFilter(req, res);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
}
